#!/bin/bash

#    / **  
#    * 文件名：
#    * 版权： Copyright 谢振斌  All Rights Reserved.  
#    * 描述： Shell模板  
#    * 修改内容：新增  
#    * 修改人： 谢振斌  
#    * 修改时间：2022-4-23  
#    */  



#    / **  
#    *〈 判断shell系统类型 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  String [linux、osx、bsd] 
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function getShellOStype()
{
    SHELL_PLATFORM='unknown';
    ## echo "[Debug] SHELL_PLATFORM=${SHELL_PLATFORM}"

    ## echo $OSTYPE | tr '[A-Z]' '[a-z]'"
    shellostypestring=`echo $OSTYPE`;
    ## echo "[Debug] shellostypestring=${shellostypestring}"

    ## 从字符串中识别shell系统类型
    case "${shellostypestring}" in
        *'linux'*   ) SHELL_PLATFORM='linux'    ;;
        *'darwin'*  ) SHELL_PLATFORM='osx'      ;;
        *'bsd'*     ) SHELL_PLATFORM='bsd'      ;;
    esac

    # if [[ $SHELL_PLATFORM == 'linux' || $SHELL_PLATFORM == 'bsd' ]]; then
    #    echo "[Debug] linux"
    # elif [[ $SHELL_PLATFORM == 'osx' ]]; then
    #    # $SHELL_PLATFORM == 'bsd'
    #    echo "[Debug] osx Shell"
    # elif [[ $SHELL_PLATFORM == 'bsd' || $SHELL_PLATFORM == 'osx'  ]]; then
    #    echo "[Debug] bad shell"
    # else
    #    echo "[Debug] unknown"
    # fi

    # 返回值
    echo $SHELL_PLATFORM;
}



#    / **  
#    *〈获得发行版本名称〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function getDistName()
{
    if grep -Eqii "Arch Linux" /etc/issue || grep -Eq "Arch Linux" /etc/*-release; then
        DISTRO='Arch Linux'
        PM='pacman'
    elif grep -Eqii "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
        DISTRO='CentOS'
        PM='yum'
    elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
        DISTRO='RHEL'
        PM='yum'
    elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
        DISTRO='Aliyun'
        PM='yum'
    elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
        DISTRO='Fedora'
        PM='yum'
    elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
        DISTRO='Debian'
        PM='apt'
    elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
        DISTRO='Ubuntu'
        PM='apt'
    elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
        DISTRO='Raspbian'
        PM='apt'
    else
        DISTRO='unknow'
    fi

    # 返回值
    echo $DISTRO;
}



#    / **  
#    *〈 安装软件 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [软件名称]  
#    * @param [参数2] [用来判断是否已经安装的软件名称，可为空，为空则，与参数1来判断是否存在]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function installSoftware()
{
    echo "[INFO] 安装软件";
    softwareName=$1;
    echo "[Debug] softwareName="${softwareName};
    # 判断是否已经安装
    #cmdStr="which ${softwareName}"
    #echo "[Debug] cmdStr="${cmdStr}
    #if [ ! -x "$( which ${softwareName} )" ]; then
    #    echo "[Debug] 未安装软="${softwareName}
    #else
    #    echo "[Debug] 已经安装软="${softwareName}
    #fi
    #exit
    softwareName2=$2;
    if [  ! $softwareName2 ];then
        echo "[INFO] 软件安装与用来判断是否安装的名称相同"
        softwareName2=${softwareName};
        echo "[Debug] softwareName2="${softwareName2};
    else
        echo "[INFO] 软件安装名称与用来判断是否安装的名称不同！";
        #softwareName2=$2;
        echo "[Debug] softwareName2="${softwareName2};
    fi
    echo "[INFO] 判断系统中是否已经存在"${softwareName2};
    if [ ! -x "$( which ${softwareName2} )" ]; then
        echo "[INFO] 软件${softwareName}未安装！"
        # 获取当前shell系统（判断是mac、还是linux）
        shellSystemType=$(getShellOStype)
        echo "[Debug] shellSystemType="${shellSystemType}
        if [ "$shellSystemType" == "linux" ]; then
            # 获取当前系统发行版本
            linuxSystemDistType=$(getDistName)
            echo "[Debug] linuxSystemDistType="${linuxSystemDistType}
            # 命令拼接
            #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
            #cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
            #echo "执行命令: ${cmdStr}"
            #${cmdStr}
            if [ "$linuxSystemDistType" == "CentOS" ]; then
                echo "[Debug] ======= CentOS"
                # 执行另一个脚本
                # /bin/bash ./zsh1.sh  
                #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
                cmdStr="yum install "${softwareName}
                echo "执行命令: ${cmdStr}"
                ${cmdStr}
            elif [ "$linuxSystemDistType" == "Arch Linux" ] ; then
                echo "[Debug] ======= Arch Linux"
                cmdStr="yay -S "${softwareName}
                echo "执行命令: ${cmdStr}"
                ${cmdStr}
            else
                echo "[Debug] ======= unknow linux dist"
                echo "[INFO] 不知道当前linux系统是什么发行版本，不知到该用什么包管理软件进行安装！软件${systemType}！"
            fi
      elif [ "$shellSystemType" == "osx" ]; then
           echo "[Debug] ======= shellSystemType是darwin，所以是 osx（macOS）"
           # 权限设置，解决部分软件无法安装问题：如 lua
           cmdStr="sudo chown -R $(whoami) /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig"
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
           cmdStr="chmod u+w /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig"
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
           # 使用软件包管理器安装软件
           cmdStr="brew install "${softwareName}
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
      else
        echo "[Debug] ======= unknow shell system type"
        echo "[INFO] 不知道当前系统是 linux bsd osx（macOS）！不知道该用什么包管理器安装软件${systemType}！"
      fi 
      if [ ! $? -eq 0 ]; then
        echo ""
        echo "[ERROR]: 安装软件${softwareName}  失败 !!！ 退出"
        exit
      fi
    else
        echo "[INFO] 软件${softwareName}已经存在！"
    fi
}




# 下載插件（git clone 模式）
function downloadPlugins()
{
    pluginsName=$1
    echo "[Debug] pluginsName="${pluginsName}

    # 拆分字符串 
    # 原理：
    # ${parameter//pattern/string} 
    # 用string来替换parameter变量中所有匹配的pattern
    # 例子：以 , 拆分字符串
    #  string="hello,shell,split,test" 
    #  array=(${string//,/ }) 
    #  echo "[Debug] 循环输出 array[]所有值="${array[1]}
    # for var in ${array[@]}
    # do
    #    echo $var
    # done
    #  参考 [Shell_Linux Shell 中实现字符串切割的几种方法](https://blog.csdn.net/u010003835/article/details/80750003)

    # 以/ 拆分字符串
    array=(${pluginsName//\// })
    # echo "[Debug] 循环输出 array[]所有值="${array[1]}
    # for var in ${array[@]}
    # do
    #   echo $var
    # done
    # echo "[Debug] array[1]="${array[1]}
    
    pluginsPath="./plugins/"${array[1]}
    # pluginsPath=${HOME}"{$HOME}/.local/share/nvim/site/pack/packer/start/"${array[1]}

    echo "[Debug] pluginsPath="${pluginsPath}

    echo "[INFO] 下載插件："${pluginsName}
    # 判断是否已经存在
    if [ ! -d "$pluginsPath" ]; then
        echo "下載（git clone ）插件： "${pluginsName}
        #URL="https://github.com/"
        #URL="https://hub.fastgit.org/"
        URL="https://ghproxy.com/https://github.com/"
        if [ -x "$(which git)" ]; then
            # 命令拼接
            # cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
            cmdStr="git clone --depth=1  "${URL}${pluginsName}" "${pluginsPath}
            echo "执行命令: ${cmdStr}"
            ${cmdStr}

            echo "[INFO] 插件"${pluginsName}"下載完成！"

        else
            echo "[ERROR]: please install git  before installation !!"
            exit
        fi
        if [ ! $? -eq 0 ]; then
            echo ""
            echo "ERROR: downloading ${pluginsName}  failed !!"
            exit
        fi
    else
        echo "[INFO] 插件${pluginsName}已经存在！"
        # 命令拼接
        # cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
        # cmdStr="cd "${pluginsPath}
        # echo "执行命令: ${cmdStr}"
        # ${cmdStr}

        # # 命令拼接
        # cmdStr="git pull"
        # echo "执行命令: ${cmdStr}"
        # ${cmdStr}

        # # 命令拼接
        # cmdStr="cd ../../"
        # echo "执行命令: ${cmdStr}"
        # ${cmdStr}
    fi
}

#    / **  
#    *〈流程控制〉  
#    *〈该脚本的主函数〉  
#    * @param [无]  
#    * @return [无]  
#    * @exception/throws [无]  
#    * @deprecated  
#    */  
function processControlMain()  
{  
    # 打印当前系统时间  
    echo "Start..."  
    date  

    # 此处是你的代码  
    # ...  
    # fun1

    # 检查与安装 oh-my-zsh   Install oh-my-zsh if not exist
    # OHMYZSH="$HOME/.oh-my-zsh"
    # if [ ! -d "$OHMYZSH" ]; then
    #   echo "Installing oh-my-zsh ..."
    #   URL="https://github.com/robbyrussell/oh-my-zsh.git"
    #   if [ -x "$(which git)" ]; then
    #     echo "git 克隆 oh-my-zsh 到 ~/.oh-my-zsh"
    #     git clone "$URL" "$OHMYZSH"
    #     /bin/bash ~/.oh-my-zsh/tools/install.sh
    #     # 重载配置
    #     source ${HOME}"/.zshrc"
    #   else
    #     echo "ERROR: please install git  before installation !!"
    #     exit
    #   fi
    #   if [ ! $? -eq 0 ]; then
    #     echo ""
    #     echo "ERROR: downloading oh-my-zsh ($URL) failed !!"
    #     exit
    #   fi;

    #   echo "move $TMPFILE to $ANTIGEN"
    # fi

    # 命令拼接
    cmdStr="mkdir -p ./plugins"
    echo "执行命令: ${cmdStr}"
    ${cmdStr}

    # 下载插件 插件包管理软件 wbthomason/packer.nvim
    # git clone --depth=1 https://ghproxy.com/https://github.com/folke/which-key.nvim 
    # git clone --depth=1 https://ghproxy.com/https://github.com/folke/which-key.nvim {$HOME}/.local/share/nvim/site/pack/packer/start
    downloadPlugins "wbthomason/packer.nvim"     # 包管理軟件
        # PackerCompile：当插件更改后，运行该命令会使更改生效
        # PackerClean：删除禁用或未使用的插件
        # PackerInstall：清理，然后安装缺少的插件，不更新已有的插件
        # PackerUpdate：清理，然后更新已有的插件和安装缺少的插件
        # PackerSync：相当与 PackerUpdate 和 PackerCompile 的结合体
        # PackerLoad：立即加载某个插件
        # 只需要记住 PackerSync 这一条命令就够用了。
    # downloadPlugins "lewis6991/impatient.nvim"   # 

    downloadPlugins "yianwillis/vimcdoc"         # 中文文档
        # 输入 :h event 查看中文文档插件是否生效

    # 目录树
        # - [nvim-tree](https://github.com/kyazdani42/nvim-tree.lua)
        # - [chadtree](https://github.com/kyazdani42/ms-jpq/chadtree)
        # - [neo-tree](https://github.com/kyazdani42/nvim-neo-tree/neo-tree.nvim)
    downloadPlugins "kyazdani42/nvim-tree.lua"      # 目录树
    downloadPlugins "kyazdani42/nvim-web-devicons"  # 图标

    # 主题美化
    # downloadPlugins "tomasr/molokai" 
    downloadPlugins "catppuccin/nvim" 

    # 状态栏
        # - [feline](https://github.com/feline-nvim/feline.nvim)
        # - [windline 内置主题可以让状态栏动起来](https://github.com/windwp/windline.nvim)
        # - [lualine](https://github.com/nvim-lualine/lualine.nvim)
    downloadPlugins "nvim-lualine/lualine.nvim" 
    downloadPlugins "windwp/windline.nvim" 

    # git
    downloadPlugins "nvim-lua/plenary.nvim"
    downloadPlugins "lewis6991/gitsigns.nvim" 

    # 支持 LSP 状态的 buffer 栏
    downloadPlugins "akinsho/bufferline.nvim" 

    # 搜索时显示条目
    downloadPlugins "kevinhwang91/nvim-hlslens"
    downloadPlugins "lukas-reineke/indent-blankline.nvim"

    # 自动匹配括号 能够自动补全另一半括号
    downloadPlugins "windwp/nvim-autopairs"

    # 快速更改单词 快速的更改一个单词为另一个单词的反意
    downloadPlugins "AndrewRadev/switch.vim"

    # 快速跳转 快速将单词定位到当前文档的某个词、字、行上
    downloadPlugins "phaazon/hop.nvim"

    # 包裹修改 快速修改外部的包裹，如将 [] 修改为 () 等
    downloadPlugins "ur4ltz/surround.nvim"

    # 显示光标下相同词汇
    downloadPlugins  "RRethy/vim-illuminate"

    # 拼写检查器 突出的显示单词的拼写错误
    downloadPlugins "lewis6991/spellsitter.nvim"

    # 自动恢复光标位置
    downloadPlugins "ethanholz/nvim-lastplace"

    # 自动会话管理
    downloadPlugins "rmagatti/auto-session"

    # 显示滚动条
    downloadPlugins "petertriho/nvim-scrollbar"
    
    # 显示网页色
    downloadPlugins "norcalli/nvim-colorizer.lua"

    # 内置终端 让默认终端变得既好看又好用
    downloadPlugins "akinsho/toggleterm.nvim"

    # undo tree
    downloadPlugins "mbbill/undotree"

    downloadPlugins "dinhhuy258/vim-local-history" 

    # 键位绑定器
    downloadPlugins "folke/which-key.nvim"       # 按键导航

    # 模糊查找 外部依赖，fd 和 repgrep , repgrep 插件
    downloadPlugins "nvim-telescope/telescope.nvim" 
    downloadPlugins "BurntSushi/ripgrep" 
    downloadPlugins "sharkdp/fd" 
    downloadPlugins "nvim-telescope/telescope-live-grep-raw.nvim" 
    downloadPlugins "nvim-telescope/telescope-ui-select.nvim" 
    downloadPlugins "nvim-telescope/telescope-fzf-native.nvim" 
    downloadPlugins "nvim-telescope//telescope-file-browser.nvim" 
    downloadPlugins "nvim-telescope/telescope-project.nvim"
    
    # 书签
    downloadPlugins "tom-anders/telescope-vim-bookmarks.nvim" 
    downloadPlugins "MattesGroeger/vim-bookmarks" 

    # 代码注释
    downloadPlugins "numToStr/Comment.nvim"
    downloadPlugins "JoosepAlviste/nvim-ts-context-commentstring"

    # 语法高亮
    downloadPlugins "nvim-treesitter/nvim-treesitter"
    downloadPlugins "p00f/nvim-ts-rainbow" # 彩虹括号

    # 自动代码补全系列插件 CMP
    downloadPlugins "hrsh7th/nvim-cmp"     #代码补全核心插件，下面都是增强补全的体验插件
    downloadPlugins "onsails/lspkind-nvim"  #为补全添加类似 vscode 的图标
    downloadPlugins "hrsh7th/vim-vsnip" #vsnip 引擎，用于获得代码片段支持
    downloadPlugins "hrsh7th/cmp-vsnip" # 适用于 vsnip 的代码片段源
    downloadPlugins "hrsh7th/cmp-nvim-lsp" # 替换内置 omnifunc，获得更多补全
    downloadPlugins "hrsh7th/cmp-path" # 路径补全
    downloadPlugins "hrsh7th/cmp-buffer"  # 缓冲区补全
    downloadPlugins "hrsh7th/cmp-cmdline" #命令补全
    downloadPlugins "f3fora/cmp-spell"  # 拼写建议
    downloadPlugins "octaltree/cmp-look"  # 字典提示
    downloadPlugins "rafamadriz/friendly-snippets"  #提供多种语言的代码片段
    downloadPlugins "lukas-reineke/cmp-under-comparator"  #让补全结果的排序更加智能
    downloadPlugins "tzachar/cmp-tabnine" # tabnine 源,提供基于 AI 的智能补全

    # 快速且完全可定制的 neovim 迎宾器。
    downloadPlugins "goolord/alpha-nvim"         # 快速且完全可定制的 neovim 迎宾器。

    # 自动切换到项目根目录
    downloadPlugins "airblade/vim-rooter"

    downloadPlugins "lunarvim/colorschemes"

    downloadPlugins "vim-local-history"   # 
    downloadPlugins "t9md/vim-choosewin"  # 窗口选择器,


    # # 命令拼接
    # cmdStr="mv  ./plugins/nvim  ./plugins/catppuccin"
    # echo "执行命令: ${cmdStr}"
    # ${cmdStr}

    downloadPlugins "projekt0n/github-nvim-theme" 


    downloadPlugins "michaelb/sniprun" 


    # downloadPlugins "junegunn/fzf" 
    # downloadPlugins "junegunn/fzf.vim" 

    downloadPlugins "kevinhwang91/rnvimr"  # 浮动ranger
    # downloadPlugins "francoiscabrol/ranger.vim" 
    # downloadPlugins "rbgrouleff/bclose.vim" 

    # downloadPlugins "lmburns/lf.nvim"

    # downloadPlugins "ptzz/lf.vim" 
    # downloadPlugins "voldikss/vim-floaterm" 
    

    # downloadPlugins "windwp/nvim-autopairs" 
    downloadPlugins "terrortylor/nvim-comment" 

    # LSP
    downloadPlugins "williamboman/nvim-lsp-installer" 
    downloadPlugins "ray-x/lsp_signature.nvim" 
    downloadPlugins "neovim/nvim-lspconfig"
    downloadPlugins "kosayoda/nvim-lightbulb"
    downloadPlugins "ray-x/lsp_signature.nvim"

    # cmp
    # downloadPlugins "hrsh7th/cmp-nvim-lsp" 
    # downloadPlugins "hrsh7th/cmp-buffer" 
    # downloadPlugins "hrsh7th/cmp-path" 
    # downloadPlugins "hrsh7th/cmp-cmdline" 
    # downloadPlugins "hrsh7th/nvim-cmp" 
    # downloadPlugins "hrsh7th/cmp-vsnip" 
    # downloadPlugins "hrsh7th/vim-vsnip" 
    # downloadPlugins "rafamadriz/friendly-snippets" 
    # downloadPlugins "onsails/lspkind-nvim" 
    
    downloadPlugins "sindrets/diffview.nvim" 
    downloadPlugins "Shatur/neovim-session-manager" 

    # 主题
    downloadPlugins "projekt0n/github-nvim-theme"

    # 输入法自动切换 mac
    downloadPlugins "lyokha/vim-xkbswitch"

    downloadPlugins "rlue/vim-barbaric" 



    # 安装 rg（ripgrep）
    installSoftware "ripgrep" "rg"

    # 安装 ack
    installSoftware "ack"

    # 安装 fzf
    installSoftware "fzf"

    # 安装 bat
    installSoftware "bat"

    # 安装 greenclip xclip xdotool dmenu
    # installSoftware "xclip"
    # installSoftware "xdotool"
    # installSoftware "greenclip"
    # installSoftware "dmenu"
    
    # 命令拼接
    cmdStr="rm -rf  "${HOME}"/.local/share/nvim/site/pack/packer/start/*"
    echo "复制以下命令执行: ${cmdStr}"
    # ${cmdStr}
    # 命令拼接
    cmdStr="cp -R "./plugins/*"  "${HOME}"/.local/share/nvim/site/pack/packer/start/"
    echo "复制以下命令执行: ${cmdStr}"
    # ${cmdStr}

    date  
    echo "The End."  
}  

# 执行入口 
# 进入脚本目录位置
cd `dirname $0`
# 获取当前脚本目录位置
shellfilepath=`pwd`'/'$0
# 打印脚本目录地址
echo "[INFO]: 脚本地址 "${shellfilepath}

if true  
#if false  
then  
    echo "[Debug] true"
    # 开始执行  从标准输入中读取并同时写入到标准输出和指定的文件上 
    ## 拼接日志文件地址
    #logfilepath=`pwd`'/'$0'.log'
    logfilepath=`pwd`'/'$0'-'$(date +%Y-%m-%d)'.log'
    ## 打印日志文件地址
    echo "[INFO]: 日志地址" ${logfilepath}
    processControlMain  | tee -a ${logfilepath}
else  
    echo "[Debug] false 函数单元测试 "  
    ## 函数单元测试  
    # downloadPlugins "zdharma/fast-syntax-highlighting"
    #installSoftware "git"
    #installSoftware "bat"
    installSoftware "ripgrep" "rg"
    #  
fi  

# 脚本结束  
